package com.gudogudo.battleworm.element {
	import com.gudogudo.battleworm.contact.ContactConfig;	
	
	import Box2D.Collision.Shapes.b2FilterData;	
	import Box2D.Dynamics.*;	
	import Box2D.Collision.Shapes.b2PolygonDef;	
	import Box2D.Common.Math.b2Vec2;	

	
//	import com.red.battleworm.AppMain;	
//	import com.red.battleworm.model.MapProxy;
	import com.gudogudo.battleworm.model.Box2DConfig;

	import Box2D.Collision.Shapes.b2ShapeDef;	

	/**
	 * @author zhangs
	 */
	public class Bullet extends AbstractElement {
		public var SPEEDMAGNITUDE : Number = 20;
		private static var WIDTH : Number = 6;
//		private static var HEIGHT : Number = 6;
		private var LEN_BULLET : Number = WIDTH/Box2DConfig.PHYSSCALE;
		private var LEN_PLAYER : Number = Math.sqrt(Player.WIDTH*Player.WIDTH+Player.HEIGHT*Player.HEIGHT)/Box2DConfig.PHYSSCALE;
		
		private var polygonDef:b2PolygonDef;
//		private var circleDef : b2CircleDef;
//		private var headDef:b2BodyDef;
		private var bodyDef:b2BodyDef;
		
		public function Bullet(m_world:b2World, px:Number, py:Number, rotation:Number, scale:Number) {
			super(m_world);
			
			polygonDef = new b2PolygonDef();
//			circleDef = new b2CircleDef();
//			headDef = new b2BodyDef();
			bodyDef = new b2BodyDef();

			initBody(px, py, rotation, scale);
		}
		
		private function initBody(px:Number, py:Number, rotation:Number, scale:Number) : void {
			var r : Number = rotation / 180 * Math.PI;
			var sin : Number = Math.sin(r);
			var cos : Number = Math.cos(r);
			
			var sd:b2PolygonDef = new b2PolygonDef();
			sd.SetAsBox(LEN_BULLET/2, LEN_BULLET/2);
			sd.density = 1;
			sd.restitution = 0.4;
//			sd.friction = 0;
			var filter : b2FilterData = new b2FilterData();
			filter.groupIndex = ContactConfig.groupIndex_Bullet;
			filter.categoryBits = 0x0001;
			filter.maskBits = 0xFFFF;
			sd.filter = filter;
			bodyDef.position.Set(px+(LEN_PLAYER+LEN_BULLET)*cos, py+(LEN_PLAYER+LEN_BULLET)*sin);
			bodyDef.fixedRotation = true;
			body = m_world.CreateBody(bodyDef);
			body.CreateShape(sd);
			body.SetMassFromShapes();
//			var mass : b2MassData = new b2MassData();
//			mass.mass = 0.0000001;
//			body.SetMass(mass);
			var maxspeed : Number = SPEEDMAGNITUDE * scale;
			if ((rotation%180+180)%180 == 90) {
				speed.y = maxspeed;
			} else if ((rotation%180+180)%180 == -90) {
				speed.y = -maxspeed;
			} else {
				speed.x = maxspeed * cos;
				speed.y = maxspeed * sin;
			}
			setSpeed(speed);
			body.SetLinearVelocity(this.speed);
		}

		public override function run() : void {
//			body.addForce(new VectorForce(false, 0, -10));
			super.run();
		}
	}
}
